<script>
export default {
  name: "dwCol",
  props: {
    // 自定义渲染的标签
    tag: {
      type: String,
      default: "div",
    },
    // 控制col在父元素中占的比例
    span: {
      type: Number,
      default: 24,
    },
    offset: Number, // 栅格左侧的间隔格数
    pull: Number, // 栅格向右移动格数
    push: Number, // 栅格向左移动格数
    xs: [Number, Object], // <768px
    sm: [Number, Object], // ≥768px
    md: [Number, Object], // ≥992px
    lg: [Number, Object], // ≥1200px
    xl: [Number, Object], // ≥1920px
  },
  // 反向递归查找第一个名为ElRow的父组件
  computed: {
    gutter() {
      let parent = this.$parent;
      while (parent && parent.$options.componentName !== "dwRow") {
        parent = parent.$parent;
      }
      return parent ? parent.gutter : 0;
    },
  },
  render(h) {
    const classList = [];
    // style样式
    const style = {};
    if (this.gutter) {
      style.paddingLeft = this.gutter / 2 + "px";
      style.paddingRight = style.paddingLeft;
    }

    // 通过比对props对象,生成对应的CSS规则  e.g el-col-offset-6 / el-col-6
    ["span", "offset", "pull", "push"].forEach((prop) => {
      if (this[prop] || this[prop] == 0) {
        classList.push(prop !== "span" ? `dw-col-${prop}-${this[prop]}` : `dw-col-${this[prop]}`);
      }
    });

    ["xs", "sm", "md", "lg", "xl"].forEach((size) => {
      // 这里分为传入对象以及数字两种情况   e.g el-col-xs-offset-4 / el-col-xs-4
      if (typeof this[size] === "number") {
        classList.push(`dw-col-${size}-${this[size]}`);
      } else if (typeof this[size] === "object") {
        let props = this[size];
        // 遍历对象
        Object.keys(props).forEach((prop) => {
          classList.push(prop !== "span" ? `dw-col-${size}-${prop}-${props[prop]}` : `dw-col-${size}-${props[prop]}`);
        });
      }
    });
    // console.log("classList", classList);

    return h(
      this.tag,
      {
        style,
        class: ["dw-col", classList],
      },
      this.$slots.default
    );
  },
};
</script>

<style scoped>
@import "./dwCol.css";
.dw-col {
  float: left;
}
</style>
